package com.yancy.controller;

import com.yancy.entity.Teacher;
import com.yancy.util.GetTeacherUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * @description:
 * @author: YancyZhang
 * @time: 2021/12/3 11:08
 */
@WebServlet("/getTeacher")
public class TeacherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*返回教师列表*/
        if(req.getParameter("method").equals("getTeacherList")){
//            PrintWriter out = resp.getWriter();
//            out.print(getTeacherList());
            req.setAttribute("list",getTeacherList());
            req.getRequestDispatcher("teacher.jsp").forward(req,resp);
        }else if(req.getParameter("method").equals("single")){
            req.setAttribute("teacher",getSingleTeacher(Integer.parseInt(req.getParameter("id"))));
            req.getRequestDispatcher("singleTeacher.jsp").forward(req,resp);
        }
    }

    public List<Teacher> getTeacherList(){
        GetTeacherUtils getTeacherUtils = new GetTeacherUtils();
        List<Teacher> list = getTeacherUtils.getTeacherList();
        return list;
    }

    public Optional<Teacher> getSingleTeacher(int id){
        GetTeacherUtils getTeacherUtils = new GetTeacherUtils();
        return getTeacherUtils.getTeacher(id);
    }
}